#coding:utf-8
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse

from .models import QUestion,Choice
from django.http import Http404

# Create your views here.

    # latest_question_list = QUestion.objects.order_by('-pub_date')[:5]
    # # output = ','.join([p.question_text for p in latest_question_list])
    # template = loader.get_template('polls/index.html')
    # context = RequestContext(request,{'latest_question_list':latest_question_list})
    # return  HttpResponse(template.render(context))
def index(request):
        latest_question_list = QUestion.objects.order_by('-pub_date')[:5]
        context = {'latest_question_list': latest_question_list}
        return render(request, 'polls/index.html', context)

# def detail(request, question_id):
#     try:
#         question = QUestion.objects.get(pk=question_id)
#     except QUestion.DoesNotExist:
#         raise Http404("Question does not exist")
#     return render(request, 'polls/datail.html', {'question': question})
def detail(request, question_id):
    question = get_object_or_404(QUestion, pk=question_id)
    return render(request, 'polls/datail.html', {'question': question})



def vote(request,question_id):
    p = get_object_or_404(QUestion, pk=question_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/datail.html', {
            'question': p,
            'error_message': "你没有选择，请选择.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()

        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

def results(request,question_id):
    """
    投票后重定向
    """
    question = get_object_or_404(QUestion,pk=question_id)
    return render(request,'polls/results.html',{'question':question})